package cn.graydove.bot.mirai

import cn.graydove.bot.core.ProcessorManager
import cn.graydove.bot.support.BotProperties
import net.mamoe.mirai.Bot
import net.mamoe.mirai.alsoLogin
import net.mamoe.mirai.event.events.NewFriendRequestEvent
import net.mamoe.mirai.event.subscribeAlways
import net.mamoe.mirai.event.subscribeFriendMessages
import net.mamoe.mirai.event.subscribeGroupMessages
import net.mamoe.mirai.join
import java.util.regex.Pattern


class Robot(private val properties: BotProperties, private val processorManager: ProcessorManager) {
    var thread: Thread? = null

    fun start() {
        val th = Thread(RobotRunnable(this));
        th.start()
        thread = th
    }

    suspend fun run() {
        val bot = Bot(properties.botQq, properties.botPassword) {
            fileBasedDeviceInfo()
        }.alsoLogin()

        val any = Regex(".*")

        bot.subscribeGroupMessages {
            matching(any) {
                processorManager.handle(Client(bot, sender, message, subject, properties))
            }
        }
        bot.subscribeFriendMessages {
            (contains("")) {
                if (sender.id == properties.hostQq) {
                    val pattern = Pattern.compile("^全群发消息[\\r\\n]+([\\s\\S]+)")
                    val matcher = pattern.matcher(message.contentToString())
                    if (matcher.find()) {
                        val sends = matcher.group(1)
                        for (i in bot.groups) {
                            i.sendMessage(sends)
                        }
                    }
                } else {
                    reply("只接受群里发送的指令")
                }
            }
        }
        bot.subscribeAlways<NewFriendRequestEvent> { event  ->
            processorManager.process(event)
        }
        bot.join()
    }

}